package SunStarView;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;

/**
 * Created by Sun.Star on 2017/1/1.
 */

public class FloatingScrollView extends ScrollView {
    public ScrollingListener listener ;
    public ScrollingLocationListener listener2 ;

    public void setListener2(ScrollingLocationListener listener2) {
        this.listener2 = listener2;
    }

    private int lastY = 0 ;
    public interface ScrollingLocationListener{
        void bottom();
        void top();
    }
    public interface ScrollingListener{
        void changeDistence(int distence);
        void isScolling();
        void stopScolling();
    }

    public void setListener(ScrollingListener listener) {
        this.listener = listener;
    }

    public FloatingScrollView(Context context) {
        super(context);
    }

    public FloatingScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FloatingScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    private boolean isLoading,noData;
    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        super.onScrollChanged(l, t, oldl, oldt);
        if(listener!=null){//如果存在监听，将竖直方向移动距离传入监听方法
            listener.changeDistence(t);//执行监听
        }
        if(t>=(getChildAt(0).getHeight()-getHeight())){
            if(listener2!=null&&!isLoading&&!noData){
                listener2.bottom();
                isLoading = true;
            }
        }
    }
    public void reLoading(){
        isLoading = true;
    }
    public void loadingComplete(){
        isLoading = false;
    }
    public void allDataIsLoad(){
        noData = true;
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(lastY == getScrollY()){
                if(listener!=null)
                listener.stopScolling();
            }else{
                handler.sendEmptyMessageDelayed(1,10);
                lastY = getScrollY();
            }
        }
    };



    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                if(listener!=null)
                    listener.isScolling();
                break;
            case MotionEvent.ACTION_MOVE:
                if(listener!=null)
                listener.isScolling();
                break;
            case MotionEvent.ACTION_UP:
                handler.sendEmptyMessageDelayed(1,10);
                break;
        }
        return super.onTouchEvent(ev);
    }
}
